// pages/consultationList/index.js
import {
  ApiGetMessageRecord,
  ApiCompleteOrder
} from "../../api/index"
const app = getApp()
Page({

  /**
   * 页面的初始数据
   */
  data: {
    baseUrl: app.globalData.$path,
    offsetTop: 0,
    Height: 150,
    /*    scrollHeight: 10, */
    contact: {},
    userInfo: {},
    message: "",
    list: [],
    loading: false,
    finish: false,
    showIcon: false,
    focus: false
  },
  endFlag: false, //是否在底部,
  /**
   * 生命周期函数--监听页面加载
   */
  async onLoad(options) {
    this.setData({
      loginType: wx.getStorageSync('loginType')
    })

    /*  this.setData({
       contact: JSON.parse(options.contact),
     }) */
    /*  contact={"icon":"files/admin/20241129/20241129131303_20241129.jpg","id":54,"doctor_id":1,"doctor_name":"内科医生","department_name":"消化内科","consultation_order_id":72,"status":2,"finish_time":null,"comment":null,"order_time":"2024-12-12 15:17-23:17"} */
    // 建立房间联系

  },

  onShow() {
    this.data.list = []
    app.setWsIsClose(true)
    //返回评价的数据
    let pages = getCurrentPages();
    let currPage = pages[pages.length - 1];
    this.setData({
      contact: wx.getStorageSync('opsPatient'),
      userInfo: wx.getStorageSync('userInfo'),
    })
    app.ws.onRoom(this.data.contact.consultation_order_id, this.acceptMessage.bind(this))
    app.ws.send({
      action: 'openPage',
      consultation_order_id: this.data.contact.consultation_order_id
    })

    if (currPage.data.comment) {
      this.setData({
        'contact.comment.id': currPage.data.comment.id
      })
      wx.setStorageSync('comment', currPage.data.comment)
    }



    if (!this.data.contact.finish_time) {
      if (this.data.contact.statusS && this.data.contact.statusS == '未开始') {
        wx.showModal({
          title: '提示',
          content: `您的就诊时间段为:${this.data.contact.order_time}，当前还未到就诊时间段，医生回复消息可能不及时`,
          icon: 'error',
          showCancel: false
        })
      }
    }

    this.getMessageList()
  },




  //再次问诊的事件
  askAgain() {
    const today = new Date();

    const year = today.getFullYear();
    const month = String(today.getMonth() + 1).padStart(2, '0'); // 月份从0开始，因此要加1
    const day = String(today.getDate()).padStart(2, '0'); // 保证日期是两位数
    /*  &&date=${} */
    wx.navigateTo({
      url: `/pages/doctorDetails/index?id=${this.data.contact.doctor_id}&&date=${year}-${month}-${day}&&index1=0&&jiezhen=1`,
    })
  },

  //处方单明细查询
  handlePreClick(e) {
    this.data.list = []
    /*     console.log(e) */
    let id = e.currentTarget.dataset.v.content.preMessageId
    wx.navigateTo({
      url: `/pagesDoctor/adviceInfoByID/index?id=${id}`,
    })
  },




  onHide() {

  },


  onReady() {
    this.endDom = this.createIntersectionObserver({
      thresholds: [0],
    }).relativeToViewport().observe("#end", (res) => {
      this.endFlag = res.intersectionRatio > 0
    })
  },

  acceptMessage(obj) {
    console.log(obj)
    if (obj.type == 'changeDoctor' && obj.order_id == this.data.contact.consultation_order_id) {
      this.setData({
        'contact.doctor_name': obj.name,
        'contact.doctor_id': obj.id
      })
      app.ws.onRoom(this.data.contact.doctor_id, this.acceptMessage.bind(this))
      // 打开服务器
      app.ws.send({
        action: 'openPage',
        consultation_order_id: this.data.contact.consultation_order_id
      })
    }



    if (this.data.contact.consultation_order_id == obj.consultation_order_id) {
      obj.type == 'prescription' ? obj.content = JSON.parse(obj.content) : obj.content
      obj.sender_icon = obj.icon
      this.data.list.push(obj)
      console.log(this.data.list)
      this.setData({
        list: this.data.list
      }, () => {
        wx.vibrateLong({
          // type: "heavy",
          // complete: (res) => {
          //   console.log('res',res)
          // }
        })
        if (this.endFlag) {
          wx.pageScrollTo({
            scrollTop: 999999999,
          })
        }
      })
    }
  },

  onPageScroll(e) {
    this.setData({
      scrollTop: e.scrollTop
    })
    if (this.data.loading || this.data.finish) return
    if (e.scrollTop === 0) {
      this.getMessageList()
    }
  },

  //点击拍照


  getMessageList() {
    this.setData({
      loading: true
    })
    const ops = {
      message_id: this.data.list[0]?.id ?? "",
      size: 20,
    }
    wx.showLoading({
      title: '加载中'
    })
    ApiGetMessageRecord({
      consultation_order_id: this.data.contact.consultation_order_id,
      ...ops
    }).then(res => {
      res.data.forEach(item => {
        if (item.type == 'prescription' || item.type == 'patientCard') {
          item.content = JSON.parse(item.content)
        }
      })
      const data = res.data || []
      const finish = !data.length
      const list = data.concat(this.data.list)
      const parmas = {
        finish
      }
      if (!finish) {
        parmas.list = list
      }
      this.setData(parmas, () => {
        if (!finish) {
          if (ops.message_id) {
            wx.pageScrollTo({
              selector: `.message_${ops.message_id}`,
              offsetTop: -100,
              duration: 0,
            })
          } else {
            wx.pageScrollTo({
              scrollTop: 999999999,
              duration: 0,
            })
          }
        }
      })
    }).finally(_ => {
      this.setData({
        loading: false
      })
      wx.hideLoading()
    })
  },


  getPatientInfo(e) {
    let orderInfo = e.currentTarget.dataset.v
    wx.navigateTo({
      url: `/pagesDoctor/patientInfo/index?orderInfo=${JSON.stringify(orderInfo)}`,
    })
  },
  onHeightchange(e) {

    let that = this
    this.setData({
      offsetTop: e.detail.height,
      showIcon: false
      /*    toView: 'message_' + (this.data.msgList[this.data.msgList.length - 1].id) */
    })
    wx.pageScrollTo({
      selector: '#end',
      offsetTop: -100, //偏移的位置
      duration: 1,
    });
    /*  var query = wx.createSelectorQuery();
     query.select('#end').boundingClientRect(function (rect) {
       that.setData({
         Height: rect.height +150
       })
     }).exec(); */
  },



  onInput(e) {
    const value = e.detail.value
    this.setData({
      message: value,
    })
  },

  onConfirm() {

    if (!this.data.message.trim()) {
      wx.showToast({
        title: '不能发送空白内容！',
        icon: "none"
      })
      this.setData({
        message: ""
      })
      return
    }
    const contact = this.data.contact
    const parmas = {
      consultation_order_id: contact.consultation_order_id,
      action: "message",
      receiver: contact.doctor_id,
      content: this.data.message,
      type: "txt",
      sender: this.data.userInfo.id,
      sender_type: "patient",
      id: Date.now()
    }
    app.ws.send(parmas, () => {
      let paramsData = {
        ...parmas,
        sender_icon: wx.getStorageSync('userInfo').icon
      }
      this.data.list.push(paramsData)
      this.setData({
        message: "",
        list: this.data.list,
        focus: true
      }, () => {
        wx.pageScrollTo({
          scrollTop: 999999999
        })
      })
    }, () => {
      wx.showToast({
        title: '发送失败',
        icon: "error"
      })
    })

  },

  openImage(e) {
    let value = e.currentTarget.dataset.v
    app.setWsIsClose(false)
    wx.chooseMedia({
      count: 3,
      mediaType: ['image'],
      sizeType: ["compressed", 'original'],
      success: (res) => {
        console.log(res)
        const contact = this.data.contact
        const data = res.tempFiles.map((item, index) => {
          return {
            consultation_order_id: contact.consultation_order_id,
            action: "message",
            receiver: contact.doctor_id,
            content: "",
            type: "img",
            sender: this.data.userInfo.id,
            sender_type: "patient",
            id: Date.now() + index,
            file: item.tempFilePath,
            sender_icon: wx.getStorageSync('userInfo').icon
          }
        })
        const list = this.data.list.concat(data)
        /*         app.ws.send(data) */
        setTimeout(() => {
          this.setData({
            message: "",
            list: list
          }, () => {
            wx.pageScrollTo({
              scrollTop: 999999999
            })
          })
        }, 1000);

      },
      complete: () => {
        app.setWsIsClose(true)
      }
    })
  },
  /**
   * 生命周期函数--监听页面卸载
   */

  iconClick() {
    this.setData({
      showIcon: !this.data.showIcon
    })
    wx.pageScrollTo({
      selector: '#end1',
      offsetTop: 0, //偏移的位置
      duration: 1,
    });
  },
  handleClick() {
    if (this.data.showIcon) {
      this.setData({
        showIcon: false
      })
    }

    /*  wx.pageScrollTo({
       selector: '#end',
       offsetTop: 0, //偏移的位置
       duration: 1,
     }); */
  },
  onUnload() {
    app.ws.send({
      action: 'openPage',
      consultation_order_id: this.data.contact.consultation_order_id
    })
    app.ws.removeRoom(this.data.contact.id)
    this.endDom && this.endDom.disconnect()
  },
  //结束咨询的按钮
  endConsultation() {
    let that = this
    wx.showModal({
      title: "是否确认结束问诊",
      success(res) {
        if (res.confirm) {
          ApiCompleteOrder(that.data.contact.consultation_order_id).then((res) => {
            if (res.code == '200') {
              wx.showToast({
                title: "结束成功",
              })
              /*   contact={"icon":"files/admin/20241129/20241129131303_20241129.jpg","id":43,"doctor_id":1,"doctor_name":"内科医生","department_name":"消化内科","consultation_order_id":58,"status":4,"finish_time":"2024-12-06 09:57:58","comment":null,"statusS":"未开始"} */
              that.setData({
                contact: res.data,
                'contact.consultation_order_id': res.data.id
              })
              /*       setTimeout(() => {
                      wx.navigateBack()
                    }, 500); */
            }

          })
        }

      }
    })

  },
  //立即评价

  evaluatedImmediatel() {
    this.data.list = []
    wx.navigateTo({
      url: `/pages/evaluatedImmediatel/index?doctor_id=${this.data.contact.doctor_id}&&order_id=${this.data.contact.consultation_order_id}`,
    })
  },
  //查看评价
  checkEvaluation() {
    this.data.list = []
    wx.navigateTo({
      url: `/pages/checkEvaluation/index?comment=${JSON.stringify(this.data.contact.comment)}`,
    })
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  // /**
  //  * 用户点击右上角分享
  //  */
  // onShareAppMessage() {

  // }
})